package com.cote.douhahou.pretloan.utils.image_akomapalend;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.text.TextUtils;

import com.cote.douhahou.pretloan.launcher.BaseContext;
import com.cote.douhahou.pretloan.utils.AkomapaLendConfigs;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class ImageConvert {

    public static final String TAG = "FileChecker";

    public static String imgDir() {
        String imgDir = BaseContext.instance().getApplicationContext().getFilesDir() + "/" + AkomapaLendConfigs.MyProduct + "Pics";
        File dirFile = new File(imgDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        return imgDir;
    }

    public static String imgFilePAth() {
        String pictureId = (System.currentTimeMillis() + "");
        String imgDir = imgDir();
        return imgDir + "/" + pictureId + ".jpg";
    }

    public static String bitmapFilePathFromURI(Context context, Uri contentURI) {
        try {
            InputStream imgInputStream = context.getContentResolver().openInputStream(contentURI);
            if (imgInputStream == null) {
                return "";
            }

            Bitmap bitmap = BitmapFactory.decodeStream(imgInputStream);
            if (bitmap == null) {
                return "";
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

            String outFilePath = imgFilePAth();
            File outFile = new File(outFilePath);

            FileOutputStream fos = new FileOutputStream(outFile);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();
            stream.flush();
            stream.close();
            imgInputStream.close();

            return outFilePath;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public static Bitmap bitmapFromFilePath(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public static String fileExtendSuffix(File file) {
        try {
            FileInputStream input = new FileInputStream(file);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(input, null, options);
            return options.outMimeType.replace("image/", ".");
        } catch (Exception e) {
            return ".jpg";
        }
    }

    public static void startConvertImage(File file, final OnImageConrtListener onOnImageConvertListener) {
        try {
            if (file != null) {
                String suffix = fileExtendSuffix(file);
                String targetDir = ImageConvert.imgDir();
                String targetPath = targetDir + "/" +
                        System.currentTimeMillis() +
                        (TextUtils.isEmpty(suffix) ? ".jpg" : suffix);

                File outFile = new File(targetPath);
                File result = ImageUtil.SINGLE.needAkomapalendCompress(300, file.getAbsolutePath()) ?
                        new ImageComress(file, outFile, false).compress() : file;

                String localPath = result.getAbsolutePath();
                Bitmap thumpBitmap = bitmapFromFilePath(localPath);

                if (onOnImageConvertListener != null) {
                    onOnImageConvertListener.onSuccess(localPath, thumpBitmap);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface OnImageConrtListener {
        void onSuccess(String localPath, Bitmap thumpImg);
    }

    public static class ImageComress {

        public File srcImg;
        private File tagImg;
        private int srcWidth;
        private int srcHeight;
        private boolean focusAlpha = false;


        public ImageComress(File srcImg, File tagImg, boolean focusAlpha) throws IOException {
            this.srcImg = srcImg;
            this.tagImg = tagImg;
            this.focusAlpha = focusAlpha;

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            options.inSampleSize = 1;

            BitmapFactory.decodeStream(new FileInputStream(srcImg), null, options);
            this.srcWidth = options.outWidth;
            this.srcHeight = options.outHeight;
        }

        private int computeSize() {
            srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
            srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;

            int longSide = Math.max(srcWidth, srcHeight);
            int shortSide = Math.min(srcWidth, srcHeight);

            float scale = ((float) shortSide / longSide);
            if (scale <= 1 && scale > 0.5625) {
                if (longSide < 1664) {
                    return 1;
                } else if (longSide < 4990) {
                    return 2;
                } else if (longSide > 4990 && longSide < 10240) {
                    return 4;
                } else {
                    return longSide / 1280 == 0 ? 1 : longSide / 1280;
                }
            } else if (scale <= 0.5625 && scale > 0.5) {
                return longSide / 1280 == 0 ? 1 : longSide / 1280;
            } else {
                return (int) Math.ceil(longSide / (1280.0 / scale));
            }
        }

        private Bitmap rotatingImage(Bitmap bitmap, int angle) {
            Matrix matrix = new Matrix();

            matrix.postRotate(angle);

            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }

        public File compress() throws IOException {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = computeSize();

            Bitmap tagBitmap = BitmapFactory.decodeStream(new FileInputStream(srcImg), null, options);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            if (ImageUtil.SINGLE.isJPG(new FileInputStream(srcImg))) {
                tagBitmap = rotatingImage(tagBitmap, ImageUtil.SINGLE.getOriAkomapalendentation(new FileInputStream(srcImg)));
            }

            tagBitmap.compress(focusAlpha ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 60, stream);
            tagBitmap.recycle();

            FileOutputStream fos = new FileOutputStream(tagImg);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();
            stream.close();

            return tagImg;
        }
    }

}
